package com.itpeng.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itpeng.pojo.Permission;
import com.itpeng.pojo.Role;
import com.itpeng.pojo.User;
import com.itpeng.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Aythor:彭彦钦
 * @Data: 2020/9/27  20:13
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查找用户
        User userInDB = userService.findByUsername(username);
        //创建集合，存入用户角色权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (userInDB != null){
            String password = userInDB.getPassword();
            //获取用户角色
            Set<Role> roles = userInDB.getRoles();
            if (roles != null){
                for (Role role : roles) {
                    //存储用户角色
                    GrantedAuthority ga = new SimpleGrantedAuthority(role.getKeyword());
                    authorities.add(ga);
                    //获取用户权限
                    Set<Permission> permissions = role.getPermissions();
                    if (permissions != null){
                        //遍历用户权限
                        for (Permission permission : permissions) {
                            ga = new SimpleGrantedAuthority(permission.getKeyword());
                            authorities.add(ga);
                        }
                    }
                }
            }
            return new org.springframework.security.core.userdetails.User(username, password, authorities);
        }
        return null;
    }
}
